﻿// ———————————————————————–
// <copyright file="XMLContentType.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// XMLContentType.cs - Library Class for the XML Content Type; A Container for valid-namespaced XML data within a ContentObject
// Project: IC.NET - EDXL Library
//
// Language:    C#, .NET 4.0
// Platform:    Windows 7, VS 2010 Beta 2
// Author:      Don McGarry MITRE Rome

/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace EDXLSharp.EDXLDELib
{
  /// <summary>
  /// Container for valid-namespaced XML data
  /// </summary>
  [Serializable]
  public partial class XMLContentType : IDEComposableObject
  {
    #region Private Member Variables

    /// <summary>
    /// A container element for collected fragments of valid XML. 
    /// </summary>
    private List<XElement> keyXMLContent;

    /// <summary>
    /// The embeddedXMLContent element is an open container for valid XML from an explicit namespaced XML Schema. 
    /// </summary>
    private List<XElement> embeddedXMLContent;

    #endregion

    #region Constructors

    /// <summary>
    /// Initializes a new instance of the XMLContentType class
    /// Default Ctor - Initializes Lists
    /// </summary>
    public XMLContentType()
    {
      this.keyXMLContent = new List<XElement>();
      this.embeddedXMLContent = new List<XElement>();
    }

    #endregion

    #region Public Accessors

    /// <summary>
    /// Gets or sets
    /// Extracts must come from the XML document contained within the embeddedXMLContent 
    /// element within the current contentObject block.
    /// 2. All content within this element MUST be explicitly namespaced as defined in the enclosing
    /// contentObject tag
    /// </summary>
    [XmlIgnore]
    public List<XElement> KeyXMLContent
    {
      get { return this.keyXMLContent; }
      set { this.keyXMLContent = value; }
    }

    /// <summary>
    /// Gets or sets
    /// The content MUST be a separately-namespaced well-formed XML document.
    /// 2. The enclosed XML content MUST be explicitly namespaced as defined in the enclosing
    /// embeddedXMLContent tag.
    /// </summary> 
    [XmlIgnore]
    public List<XElement> EmbeddedXMLContent
    {
      get { return this.embeddedXMLContent; }
      set { this.embeddedXMLContent = value; }
    }

    /// <summary>
    /// Gets or sets
    /// XML Serialization Object for KeyXMLContent
    /// </summary>
    [XmlElement(ElementName = "keyXMLContent", Order = 0)]
    public XElement[] KeyXMLContentXML
    {
      get
      {
        if (this.keyXMLContent.Count == 0)
        {
          return null;
        }
        else
        {
          return this.keyXMLContent.ToArray();
        }
      }

      set
      {
        if (value != null)
        {
          this.keyXMLContent = value.ToList();
        }
      }
    }

    /// <summary>
    /// Gets or sets
    /// XML Serialization Object for EmbeddedXMLContent
    /// </summary> 
    [XmlElement(ElementName = "embeddedXMLContent", Order = 1)]
    public XElement[] EmbeddedXMLContentXML
    {
      get
      {
        if (this.embeddedXMLContent.Count == 0)
        {
          return null;
        }
        else
        {
          return this.embeddedXMLContent.ToArray();
        }
      }

      set
      {
        if (value != null)
        {
          this.embeddedXMLContent = value.ToList();
        }
      }
    }

    #endregion

    #region Public Member Functions

    /// <summary>
    /// Adds Key XML Content To The List
    /// </summary>
    /// <param name="keyXML">Valid XML Element That Is Outside the DE Namespace</param>
    public void AddKeyXML(XElement keyXML)
    {
      this.CheckNameSpace(keyXML);
      this.keyXMLContent.Add(keyXML);
    }

    /// <summary>
    /// Adds Embedded XML Content To The List
    /// </summary>
    /// <param name="embeddedXML">Valid XML Element That Is Outside the DE Namespace</param>
    public void AddEmbeddedXML(XElement embeddedXML)
    {
      this.CheckNameSpace(embeddedXML);
      this.embeddedXMLContent.Add(embeddedXML);
    }

    /// <summary>
    /// Writes this Object to XML
    /// </summary>
    /// <param name="xwriter">Existing XML Document</param>
    internal override void WriteXML(XmlWriter xwriter)
    {
      this.Validate();
      if (this.keyXMLContent.Count != 0)
      {
        foreach (XElement xe in this.keyXMLContent)
        {
          xwriter.WriteStartElement("keyXMLContent");
          xe.WriteTo(xwriter);
          xwriter.WriteEndElement();
        }
      }

      if (this.embeddedXMLContent.Count != 0)
      {
        foreach (XElement xe in this.embeddedXMLContent)
        {
          xwriter.WriteStartElement("embeddedXMLContent");
          xe.WriteTo(xwriter);
          xwriter.WriteEndElement();
        }
      }
    }

    /// <summary>
    /// Reads This Object From An Existing XML Node
    /// </summary>
    /// <param name="rootnode">Existing XML Node</param>
    internal override void ReadXML(XmlNode rootnode)
    {
      XElement xe;
      foreach (XmlNode node in rootnode.ChildNodes)
      {
        if (String.IsNullOrEmpty(node.InnerText) && String.IsNullOrEmpty(node.InnerXml))
        {
          continue;
        }

        switch (node.LocalName)
        {
          case "embeddedXMLContent":
            xe = XElement.Parse(node.InnerXml);
            this.CheckNameSpace(xe);
            this.embeddedXMLContent.Add(xe);
            break;
          case "keyXMLContent":
            xe = XElement.Parse(node.InnerXml);
            this.CheckNameSpace(xe);
            this.keyXMLContent.Add(xe);
            break;
          case "#comment":
            break;
          default:
            throw new FormatException("Invalid value: " + node.Name + "found in ValueList Type");
        }
      }

      this.Validate();
    }

    #endregion

    #region Private Member Functions

    /// <summary>
    /// Validates This Message Element For Required Values and Conformance
    /// </summary>
    protected override void Validate()
    {
    }

    /// <summary>
    /// Checks Whether The Input XElement is in the DE 1.0 Namespace
    /// </summary>
    /// <param name="xe">XML ELement or Document Object</param>
    private void CheckNameSpace(XElement xe)
    {
      if (xe == null)
      {
        throw new ArgumentNullException("Input XElement can't be null");
      }

      XNamespace name = xe.Name.Namespace;
      if (name.NamespaceName == EDXLConstants.EDXLDE10Namespace)
      {
        throw new ArgumentException("Embedded and Key XML Content Must Be Outside the " + EDXLConstants.EDXLDE10Namespace + " Namespace");
      }
      else if (name.NamespaceName == String.Empty)
      {
        throw new ArgumentException("Embedded and Key XML Content Must Be Explicitly Namespaced");
      }
    }

    #endregion
  }
}
